package;

import game.views.ViewManger;
import game.worlds.PracticeArenaWorld;
import hx.ui.UIAssets;
import haxe.io.Path;
import game.worlds.GameWorld;
import hx.utils.URLQuery;
import openfl.Lib;
import hx.layout.AnchorLayoutData;
import hx.ui.UIManager;
import hx.assets.Assets;
import hx.display.Button;
import game.views.ExchangeEffect;
import game.views.StartView;
import game.utils.KeybarodTools;
import hx.utils.SceneManager;
import hx.display.Stage;

@:build(hx.macro.AutoImport.build("Source/game/views", "game.views"))
@:build(hx.macro.AutoImport.build("Source/game/buff", "game.buff"))
class GameMain extends Stage {
	override function onStageInit() {
		super.onStageInit();

		// 初始化键盘
		KeybarodTools.init();

		#if (!editer && game)
		var fps = new hx.display.FPS();
		this.topView.addChild(fps);
		#if editer
		fps.layoutData = new AnchorLayoutData(null, null, 58 + 36 + 16 + 4, 240);
		fps.scaleX = fps.scaleY = 0.6;
		#else
		fps.layoutData = new AnchorLayoutData(null, null, null, 0);
		fps.scaleX = fps.scaleY = 0.6;
		#end
		#end

		var assets = new Assets();
		assets.loadSound("assets/sounds/start_main.mp3");
		assets.loadSound("assets/sounds/click.mp3");
		assets.loadSound("assets/sounds/selected.mp3");
		assets.loadUIAssets("assets/views/LoadRoleView.xml");
		#if editer
		assets.loadAtlas("assets/ui/atlas/UIAtlas.png", "assets/ui/atlas/UIAtlas.xml");
		#end
		assets.onComplete((a) -> {
			onPlayGame();
		});
		assets.start();
		UIManager.bindAssets(assets);

		// 设置默认的点击音效
		Button.clickSoundEffectId = "click";

		this.updateEnabled = true;
	}

	override function onUpdate(dt:Float) {
		super.onUpdate(dt);
		ViewManger.update();
	}

	private function onPlayGame() {
		var url = Lib.current.loaderInfo.url;
		if (url != null && url.indexOf("?abn") != -1) {
			var query = URLQuery.parse(url);
			if (query["abn"] != null) {
				trace("预览abn人物数据包", query["abn"]);
				var abnPath = query["abn"];
				var abnId = Path.withoutDirectory(Path.withoutExtension(abnPath));
				var gameWorld = new PracticeArenaWorld({
					roles: [
						{
							id: abnId,
							loadType: ABN_DATA,
							path: abnPath
						}
					],
					player1: abnId,
					player2: abnId
				});
				if (query["map"] != null)
					gameWorld.mapId = query["map"];
				gameWorld.stateDebug = true;
				gameWorld.debug = false;
				SceneManager.getInstance().replaceScene(gameWorld);
				game.utils.TestTools.init();
				return;
			}
		}
		#if editer
		var editer = new game.editer.EditerStage();
		SceneManager.getInstance().replaceScene(editer);
		#else
		// 切换效果
		SceneManager.getInstance().defaultSceneExchangeEffect = ExchangeEffect;
		var view = new StartView();
		SceneManager.getInstance().replaceScene(view);
		game.utils.TestTools.init();
		#end
	}
}
